﻿using System;
using System.Data.SQLite;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    public partial class MainForm
    {
        private static bool PromptForFiles(OpenFileFormMode pMode)
        {
            Program.OpenFilesForm = new OpenFiles(
                String.Empty,
                String.Empty,
                pMode);
            return Program.OpenFilesForm.ShowDialog() == DialogResult.OK;            
        }

        private bool LoadFiles(OpenFileFormMode pMode)
        {
            Program.LoadingForm = new Loading(
                Program.OpenFilesForm.GetSQLiteChoice,
                Program.OpenFilesForm.GetSQLiteFileMode,
                Program.OpenFilesForm.GetRotasTemplatesChoice,
                Program.OpenFilesForm.GetRotasFileMode)
                                      {
                                          Height = SystemInformation.CaptionHeight -
                                                   (SystemInformation.FixedFrameBorderSize.Height*2)
                                      };
            var _result = Program.LoadingForm.ShowDialog();
            if (_result == DialogResult.Abort)
            {
                var _exception = Program.LoadingForm.GetException;
                if (_exception != null)
                {
                    if (_exception.GetType() == typeof(SerializationException))
                    {
                        ErrorNoticeInvalidDataFileFormat();
                        return PromptAndLoadFiles(pMode); // go to Start
                    }
                    if (_exception.GetType() == typeof(SQLiteException))
                    {

                    }
                    else
                    {
                        MessageBox.Show(
                            String.Concat(
                            Program.LoadingForm.GetFailMessage,
                            Environment.NewLine,
                            _exception.Message));
                    }
                }
                else
                {
                    MessageBox.Show(Program.LoadingForm.GetFailMessage);
                }
                return PromptAndLoadFiles(pMode); // go to Start
                /* note that even in an event of "deep recursion" - if there is, say,
                 * 20 errors in a row (and therefore 20 PromptAndLoadFiles executions,
                 * embedded within eachother), it'pShift still the FINAL result - true / false -
                 * that will bubble up the stack */
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <remarks>
        /// To be called once the files are loaded (by SQLiteAccess class and into Program.CurrentFile variable)
        /// </remarks>
        private void ReadFilesIn()
        {
            SuspendLayout();

            lbEmployeesRequest_Populate();
            
            dgridRequestsPending_Populate();
            lbEmployeesRequests_SelectedValueChanged(null, null); // calls dgridRequests_Populate

            cbHideArchiveOnes.Checked = false;
            sheetCalendar.Refresh();

            CURRENTFILE_SetEventHandlers();
            LoadDefaultRota();
            cbYear_Refresh();
            SQLiteAccess_OnDataChanged(
                -1,
                new[] { 0, 1, 2, 3 },
                (DateTime?)null,
                (DateTime?)null);
            
            if (SQLiteAccess.IsEmpty)
            {
                CollapseStaffDetails();
                SwitchToTab(tpStaff);
                MessageBox.Show(
                    Resources.MESSAGEBOX_INFO_EmptyDatabaseOpened_Message,
                    Resources.MESSAGEBOX_INFO_EmptyDatabaseOpened_Caption,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            else
            {
                UncollapseStaffDetails();
            }
            ResumeLayout();
        }

        private bool PromptAndLoadFiles(OpenFileFormMode pMode)
        {            
            if (!PromptForFiles(pMode))
            {
                return false; // user cancelled: we return false (for failure)
            }            
            if (!LoadFiles(pMode))
            {
                return false;
            }                        
            ReadFilesIn();
            return true; // everything went all right
        }

        public void SaveFile()
        {
            SaveFileAs(String.Empty);
        }

        public void SaveFileAs(string pFileName)
        {
            var fileName = (pFileName == String.Empty) ?
                Program.CurrentFile.FileName :
                pFileName;
            Hourglass(true);
            var exception = File.Exists(fileName) ?
                Program.CurrentFile.SaveTo(File.OpenWrite(fileName)) :
                Program.CurrentFile.SaveTo(File.Create(fileName));
            if (exception != null)
            {
                Hourglass(false);
                ErrorNoticeFileSaving(exception);                
                return;
            }
            CURRENTFILE_SetEventHandlers();
            Hourglass(false);
        }
    }
}
